// ignore_for_file: public_member_api_docs, sort_constructors_first
// ignore_for_file: avoid_print

import 'dart:async';

import 'package:audio_waveforms/audio_waveforms.dart';
import 'package:flutter/material.dart';

enum SendContentType {
  voice,

  text,
}

enum SoundsMessageStatus {
  /// 默认状态 未交互/交互完成
  none,

  /// 录制
  recording,

  /// 取消录制
  canceling;

  String get title {
    switch (this) {
      case none:
        return 'Long Press Recording';
      case recording:
        return 'Release Send';
      case canceling:
        return 'Release Cancel';
    }
  }
}

/// 录音类
class SoundsRecorderController {
  SoundsRecorderController();

  /// 录音操作时间内的音频振幅集合，最新值在前
  /// [0.0 ~ 1.0]
  final amplitudeList = ValueNotifier<List<double>>([]);

  /// 音频地址
  final path = ValueNotifier<String?>('');

  /// 录音操作的状态
  final status = ValueNotifier(SoundsMessageStatus.none);

  final RecorderController recorderController = RecorderController()
    ..androidEncoder = AndroidEncoder.aac
    ..androidOutputFormat = AndroidOutputFormat.mpeg4
    ..iosEncoder = IosEncoder.kAudioFormatMPEG4AAC
    ..sampleRate = 44100;

  final duration = ValueNotifier<int>(0);
  Timer? _timer;
  Timer? _durationTimer;

  /// 开始录制前就已经结束
  /// 用于录音还未开始，用户就已经松开手指结束录制的特殊情况
  //  bool beforeEnd = false;
  /// 用途同上
  Function(String? path, int time)? _onAllCompleted;

  void startOrStopRecording({
    /// 录制时间
    ValueChanged<int>? onDurationChanged,

    /// 结束录制
    /// 录制时长超过60s时，自动断开的处理
    required Function(String? path, int time) onCompleted,
  }) async {
    try {
      reset();
      _onAllCompleted = onCompleted;

      updateStatus(SoundsMessageStatus.recording);

      // 记录时间
      _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
        duration.value++;
        if (duration.value >= 60) {
          endRec();
        }
        onDurationChanged?.call(duration.value);
      });
      _durationTimer =
          Timer.periodic(const Duration(milliseconds: 50), (Timer t) {
        amplitudeList.value = recorderController.waveData.reversed.toList();
      });

      await recorderController.record(); // Path is optional
    } catch (e) {
      debugPrint(e.toString());
    } finally {}
  }

  /// 重置
  reset() {
    _timer?.cancel();
    _durationTimer?.cancel();
    duration.value = 0;
  }

  void dispose() {
    reset();
    recorderController.dispose();
  }

  /// 更新状态
  updateStatus(SoundsMessageStatus value) {
    status.value = value;
  }

  void endRec() async {
    if (recorderController.isRecording &&
        status.value == SoundsMessageStatus.recording) {
      recorderController.reset();

      path.value = await recorderController.stop();

      if (path.value?.isNotEmpty == true) {
        debugPrint(path.value);
        // debugPrint("Recorded file size: ${File(path.value!).lengthSync()}");
      }
      _onAllCompleted?.call(path.value, duration.value);
    } else {
      _onAllCompleted?.call(null, 0);
    }
    reset();
  }
}
